<template>
  <div class="product-management">
    <a-row :gutter="16" class="seach-row">

      <a-col :span="8">
        <a-form-item label="评价等级" style="display: flex;align-items: center">
          <a-select placeholder="请选择评价等级" style="width: 290px">
            <a-select-option value="all">全部</a-select-option>
            <a-select-option value="good">好评</a-select-option>
            <a-select-option value="neutral">中评</a-select-option>
            <a-select-option value="bad">差评</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="评价状态" style="display: flex;align-items: center">
          <a-select placeholder="请选择评价状态" style="width: 290px">
            <a-select-option value="all">全部</a-select-option>
            <a-select-option value="pending">未回复</a-select-option>
            <a-select-option value="replied">已回复</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="评价时间" style="display: flex;align-items: center">
          <a-range-picker/>
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-button type="primary" html-type="submit">查询</a-button>
        <a-button style="margin-left: 8px">重置</a-button>
      </a-col>
    </a-row>
    <!--tab栏-->
    <a-tabs style="margin-bottom: 0 !important;" :active-key="defaultActive" @change="handleChange">
      <a-tab-pane key="all" :tab="`全部评价（${allCount} ）`"></a-tab-pane>
      <a-tab-pane key="pending" :tab="`未回复评价（${pendingCount}）`"></a-tab-pane>
      <a-tab-pane key="replied" :tab="`已回复评价（${repliedCount}）`"></a-tab-pane>
    </a-tabs>
    <!-- 表格 -->
    <a-table :data-source="filteredData" :columns="columns" rowKey="id" class="tab-cont">
      <template slot="goodsImages" slot-scope="text, record">
        <img :src="record.goodsImages" alt="商品图片" style="width: 50px; height: 50px; margin-right: 10px;">
        <span>{{ record.goodsName }}</span>
      </template>
      <template slot="action" slot-scope="text, record">
        <a-button type="link" @click="handleDetail(record)">查看订单</a-button>
      </template>
    </a-table>
    <a-modal
        title="查看订单"
        :visible="detailModalVisible"
        @ok="handleSelCancel"
        @cancel="handleSelCancel">
      <a-form-item label="评价商品">
        <a-input v-model="currentRecord.goodsName"/>
      </a-form-item>
      <a-form-item label="用户信息">
        <a-input v-model="currentRecord.userName"/>
      </a-form-item>
      <a-form-item label="评价等级">
        <a-input v-model="currentRecord.goodsScore"/>
      </a-form-item>
      <a-form-item label="评价内容">
        <a-input v-model="currentRecord.content"/>
      </a-form-item>
      <a-form-item label="回复内容">
        <a-input v-model="currentRecord.replyContent"/>
      </a-form-item>
      <a-form-item label="状态">
        <a-input v-model="currentRecord.reply"/>
      </a-form-item>
      <a-form-item label="评价时间">
        <a-input v-model="currentRecord.createTime"/>
      </a-form-item>
    </a-modal>
  </div>
</template>

<script>
import {Modal} from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import axios from "axios";

export default {
  components: {
    'a-modal': Modal,
  },

  data() {
    return {
      allCount: 0,
      pendingCount: 0,
      repliedCount: 0,
      defaultActive: 'all',
      detailModalVisible: false,// 查看订单弹窗
      currentRecord: {},//当前操作的订单
      filteredData: [],//过滤后的数据
      columns: [
        {
          title: '评价商品',
          dataIndex: 'goodsName',
          id: 'goodsName',
          scopedSlots: {customRender: 'goodsImages'},
        },
        {
          title: '用户信息',
          dataIndex: 'userName',
          id: 'userName',
        },
        {
          title: '评价等级',
          dataIndex: 'evaluationLabel',
          id: 'evaluationLabel',
        },
        {
          title: '评价内容',
          dataIndex: 'content',
          id: 'content',
        },
        {
          title: '回复内容',
          dataIndex: 'replyContent',
          id: 'replyContent',
        },
        {
          title: '状态',
          dataIndex: 'reply',
          id: 'reply',
        },
        {
          title: '评价时间',
          dataIndex: 'createTime',
          id: 'createTime',
        },
        {
          title: '操作',
          dataIndex: 'action',
          id: 'action',
          scopedSlots: {customRender: 'action'},
        }
      ],
      dataSource: [
        // {
        //   id: '1',
        //   goodsImages: require('@/pages/list/menu/images/索尼 Xperia 1 IV.png'),
        //   goodsName: '商品1',
        //   userName: '用户1',
        //   goodsScore: '好评',
        //   content: '评价内容1',
        //   reply: '待回复',
        //   createTime: '2023-08-10',
        // },
        // {
        //   id: '2',
        //   goodsImages: require('@/pages/list/menu/images/索尼 Xperia 1 IV.png'),
        //   goodsName: '商品2',
        //   userName: '用户2',
        //   goodsScore: '中评',
        //   content: '评价内容2',
        //   reply: '已回复',
        //   createTime: '2023-08-11',
        // },
        // 更多数据...
      ],
    }
  },
  methods: {
    getEvaluationLabel(score) {
      if (score >= 4) {
        return '好评';
      } else if (score === 3) {
        return '中评';
      } else {
        return '差评';
      }
    },
    async fetchshop() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/goods/QueryCommentAll`, {
          headers: {
            Authorization: `Bearer ` + localStorage.getItem('token')
          }
        });

        if (response.data.code === 200) {
          const orderData = response.data.data;
          // 遍历订单数据，设置 username
          orderData.forEach(item => {
            item.userName = item.userName == null || item.userName === "" ? "乐购" + item.mobile : item.userName;
          });
          this.dataSource = orderData;

          // 给每个商品添加评价标签
          this.filteredData = orderData.map(item => ({
            ...item,
            evaluationLabel: this.getEvaluationLabel(item.goodsScore)
          }));
        } else {
          console.error('评论信息失败:', response.data.msg);
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },
    handleChange(id) {
      this.defaultActive = id;
      this.filterDataSource(); // 根据选中的标签过滤数据
    },
    filterDataSource() {
      let filtered = [...this.dataSource]; // 复制原始数据以避免直接修改

      // 根据当前激活的标签页来过滤数据
      switch (this.defaultActive) {
        case 'all':
          break;
        case 'pending':
          filtered = filtered.filter(item => item.reply === '未回复');
          break;
        case 'replied':
          filtered = filtered.filter(item => item.reply === '已回复');
          break;
        default:
          break; // 如果没有匹配的情况，就不做任何处理
      }

      // 给每个商品添加评价标签
      this.filteredData = filtered.map(item => ({
        ...item,
        evaluationLabel: this.getEvaluationLabel(item.goodsScore)
      }));

      // 更新计数器或其他操作（例如：更新某些统计信息）
      // this.updateCounts();
    },
    updateCounts() {
      // 计算每个标签的计数
      this.allCount = this.filteredData.length; // 全部评价的数量
      this.pendingCount = this.filteredData.filter(item => item.reply === '未回复').length; // 未回复评价的数量
      this.repliedCount = this.filteredData.filter(item => item.reply === '已回复').length; // 已回复评价的数量
    },
    handleDetail(record) {
      this.currentRecord = record;
      this.detailModalVisible = true;
    },
    handleSelCancel() {
      this.detailModalVisible = false;
    },
  },
  mounted() {
    this.fetchshop()
    this.filterDataSource(); // 初始化时过滤数据
  },
};
</script>

<style scoped>
.tab-cont {
  max-width: 100%;
  overflow-x: auto;
  background-color: white;
}
</style>
